package specialHandle

import (
	"context"
	"fmt"
	"net/http"
)

//责任链过滤器，用于鉴权 白名单 参数验证等等的特殊处理（如果需要的话）

var WebFilter *CombinedFunc
var WebFilterFunc FilterFuncChain
var myContext MyContext

type MyContext struct {
	context.Context
	KeyValue map[string]bool
}

type FilterFunc func(*MyContext, http.ResponseWriter, *http.Request)

type FilterFuncChain []FilterFunc

type CombinedFunc struct {
	CF    FilterFuncChain
	MyCtx *MyContext
}

func init() {
	myContext = MyContext{Context: context.TODO(), KeyValue: map[string]bool{"key": false}}
	AddWebFilterFunc(F1)
}
func DoFilter(cf *CombinedFunc, w http.ResponseWriter, r *http.Request) bool {
	for _, f := range cf.CF {
		f(cf.MyCtx, w, r)
		continued := cf.MyCtx.KeyValue["key"]
		fmt.Println("result:", continued)
		if !continued {
			return false
		}
	}
	return true
}
func CombinedFilter(ctx *MyContext, ff ...FilterFunc) *CombinedFunc {
	return &CombinedFunc{
		CF:    ff,
		MyCtx: ctx,
	}
}

// AddWebFilterFunc 封装一个添加过滤链的功能
func AddWebFilterFunc(ff ...FilterFunc) {
	WebFilterFunc = append(WebFilterFunc, ff...)
	WebFilter = CombinedFilter(&myContext, WebFilterFunc...)
}

// StartWebFilter 调用过滤链
func StartWebFilter(w http.ResponseWriter, r *http.Request) bool {
	return DoFilter(WebFilter, w, r)
}
func F1(ctx *MyContext, w http.ResponseWriter, r *http.Request) {

	ctx.KeyValue["key"] = true
}
